package org.dlx.common;

//双向链表 添加删除
public class List
{
    private Node _first;

    public void pushBack(int value){
        Node n = new Node(value);
        if(_first == null){
            _first = n;
        }else{
            Node tail = _first;
            while(tail.getNext() != null) {
                tail = tail.getNext();
            }
            tail.setNext(n);
            n.setPrev(tail);
            //n.setNext(null);
        }
    }

    public int popBack(){
        if(_first == null)
            throw new RuntimeException("没数据");
        Node tail = _first;
        while(tail.getNext() != null)
            tail = tail.getNext();
        tail.getPrev().setNext(null);
        tail.setPrev(null);
        return tail.getValue();
    }

    //删除节点
    public void remove(Node n) {
        if(_first == null)
            throw new RuntimeException("没数据");

        if(_first == n){//首节点
            //prev为空
            _first = n.getNext();
            n.getNext().setPrev(null);
        }else{//中间节点
            n.getPrev().setNext(n.getNext());
            if(n.getNext() != null)
                n.getNext().setPrev(n.getPrev());
        }
    }

    public static class Node{
        int value;
        Node prev;
        Node next;
        public Node(int v){
            value = v;
        }
        public int getValue()
        {
            return value;
        }

        public void setValue(int value)
        {
            this.value = value;
        }

        public Node getPrev()
        {
            return prev;
        }

        public void setPrev(Node prev)
        {
            this.prev = prev;
        }

        public Node getNext()
        {
            return next;
        }

        public void setNext(Node next)
        {
            this.next = next;
        }
    }
}
